//
//  OAuthViewController.swift
//  Weibo
//
//  Created by 梁智 on 15/11/25.
//  Copyright © 2015年 lzfree. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController {

    private lazy var webView = UIWebView()
    
    // MARK: - 监听方法
    @objc private func close() {
        SVProgressHUD.dismiss()
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    /// 自动填充用户名和密码 － web 注入（以代码的方式向web页面添加内容）
    @objc private func autoFill() {
        
        let js = "document.getElementById('userId').value = 'lzfree@qq.com';" +
        "document.getElementById('passwd').value = 'liangzhi1314';"
        
        // 让 webView 执行 js
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    
    // MARK: - 设置界面
    override func loadView() {
        view = webView
        
        // 设置代理
        webView.delegate = self
        
        // 设置导航栏
        title = "登录新浪微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "autoFill")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.webView.loadRequest(NSURLRequest(URL: NetworkTools.sharedTools.oauthURL))
    }

}

extension OAuthViewController: UIWebViewDelegate {
    
    /// 将要加载请求的代理方法
    ///
    /// - parameter webView:        webView
    /// - parameter request:        将要加载的请求
    /// - parameter navigationType: 页面跳转的方式
    ///
    /// - returns: 返回 false 不加载，返回 true 继续加载
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
    
        // 目标：如果是百度，就不加载
        // 1. 判断访问的主机是否是 www.baidu.com
        guard let url = request.URL where url.host == "www.baidu.com" else {
            
            return true
        }
        
        guard let query = url.query where query.hasPrefix("code=") else {
            print("取消授权了")
            close()
            return false
        }
        
        
        let code = query.substringFromIndex("code=".endIndex)
        
        //print(query)
        print("授权码是" + code)
        
        UserAccountViewModel.sharedUserAccount.loadAccessToken(code) { (isSuccess) -> () in
            if !isSuccess {
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
                
//                delay(0.5, callFunc: { () -> () in
//                    self.close()
//                })
                delay(0.5) { self.close() } // 尾随闭包
                
                
                return
            }
            
            print("成功了")
            self.dismissViewControllerAnimated(false, completion: { () -> Void in
                SVProgressHUD.dismiss()
                // 发送通知
                NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootViewControllerNotification, object: "OAuthViewController")
            })
        }
        
        return false
        
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
}